<template>
  <page-dialog :title="dialogInfo.title" v-model:visible="shows" :width="dialogInfo.width" :bt-list="dialogInfo.btList">
    <div class="filter-wrapper">
      <NewPageFilter v-model:query="filterInfo.query.queryMap" :query-more-json="true"
        :filter-list="filterInfo.searchList" :isFromDialog="true" :filter-btn="filterInfo.searchBtn"
        :clear-type="clearType" :slip-select-request="slipSelectRequest">
      </NewPageFilter>
    </div>
    <div class="filter-wrapper">
      <NewPageFilter :filter-btn="filterInfo.btnList">
      </NewPageFilter>
    </div>
    <!-- 条件栏 -->
    <DialogTable v-model:data="tableInfo.data" :field-list="tableInfo.fieldList"
      :handle="tableInfo.handle" :highlight-row="false" :tabIndex="true" :check-box="false" :isDynamic="false" :pager="false"
      :row-class-name="tableRowClassName">
      <template v-slot:col-udiCode="scope">
        <el-input v-model="scope.row.udiCode" />
      </template>
      <template v-slot:col-udiImageUrl="scope">
        <!-- <div v-if="scope.row.udiImageUrl" class="showImage" @click="viewImg(scope.row, scope.$index)" @mouseover="onMouseOverTable(item.value)"> -->
        <div v-if="scope.row.udiImageUrl" class="showImage" @mouseover="handleMouseOver"  @mouseleave="handleMouseLeave">
          <div
            class="image-tag"
            v-if="hovered"
          >
            <span @click="handlePreviewWin(action + scope.row.udiImageUrl)" style="font-size: 20px; color: #ffffff; cursor: pointer;">
              <el-icon >
                <Search  />
              </el-icon>
            </span>
            <span @click="viewImg(scope.row, scope.$index)" style="font-size: 20px; color: #ffffff; cursor: pointer;">
              <el-icon>
                <ZoomIn />
              </el-icon>
            </span>
            <span @click="handleRemove(scope.$index)" style="font-size: 20px; color: #ffffff; cursor: pointer;">
              <el-icon>
                <Delete />
              </el-icon>
            </span>
            <!-- <span @click="downFiles('/pub' + scope.row.udiImageUrl)" style="font-size: 20px; color: #ffffff; cursor: pointer;">
              <el-icon>
                <Download />
              </el-icon>
            </span> -->
          </div>
          <el-image class="image" :src="action + scope.row.udiImageUrl"></el-image>
        </div>
        <tableUploadImg v-else title="上传UDI图片" :index="scope.$index" @upDateUpload="upDateUpload" />
      </template>
    </DialogTable>
    <EleGallery
      v-if="viewImgInfo.visible"
      v-model:show-dialog="viewImgInfo.visible"
      :file-list="viewImgInfo.list"
      :title="viewImgInfo.title"
      :show-delete="true"
      :multiple-sheets="true"
      @callbackEle="callbackEle"
    />
  </page-dialog>
</template>
<script setup>
import { getUdiReceivingOrderDetailBindPage, creatdUdiReceivingOrderDetailBind, exportUdiReceivingOrderDetailBind } from '@/api/udi.js'
import { getCustomizeSetting } from '@/api/customize'
import { exportTemplateImage } from '@/api/pub'
import EleGallery from '@/components/NewUpload/eleGallery'
import tableUploadImg from '@/components/NewUpload/tableUploadImg'
import axios from 'axios'

const { proxy } = getCurrentInstance()

const emit = defineEmits()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  tableRow: {
    type: Object,
    default: () => {
      return {}
    }
  }
})
const action = ref(axios.defaults.baseURL + '/pub')
const shows = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件shows
  },
})

// 过滤相关配置
// 过滤相关配置
const clearType = ref(true)
const selectRow = ref({})
const slipSelectRequest = ref(true)
const filterInfo = reactive({
  copyQueryMap: {},
  query: {
    sortString: '',
    page: false,
    queryMap: {},
    queryParams: {
      orderId: props.tableRow.id,
    },
    customizeUserVO: {},
  },
  searchList: [

  ],
  searchBtn: [
    { type: 'button', label: '查询', event: search },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    { type: 'button', label: '导出Excel', event: exportExcel },
  ]
})
const viewImgInfo = ref({
  visible: false,
  list: [],
  title: 'UDI图片',
  row: {},
  index: '',
})
// 表格相关
const tableInfo = reactive({
  data: [],
  api: '',
  fieldList: [

  ],
})
const hovered = ref(false)
// 弹窗相关
const dialogInfo = reactive({
  title: 'UDI码绑定',
  width: '80%',
  btLoading: false,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    { label: '保存', event: handleSave, show: true },
  ],
})

function getList() {
  proxy.$nextTick(() => {
    let query = proxy.$fn.deepClone(filterInfo.query)
    query.queryMap = {}
    getUdiReceivingOrderDetailBindPage(query).then(res => {
      if (res && res.success) {
        tableInfo.data = res.data
      }
    })
  })
}
function search() {
  proxy.$nextTick(() => {
    tableInfo.data.map(item => {
      item.isChoice = false
    })
    let query = proxy.$fn.deepClone(filterInfo.query)
    if(!query.queryMap.commonName.value && !query.queryMap.productCode.value && !query.queryMap.standard.value && !query.queryMap.udiCode.value && !query.queryMap.factoryMainCode.value && !query.queryMap.factorySubCode.vlaue && !query.queryMap.uniqueCode.value){
      proxy.$message({
        type: 'warning',
        duration: 3500,
        message: '请输入查询条件',
        showClose: true,
      })
      return
    }
    getUdiReceivingOrderDetailBindPage(query).then(res => {
      if (res && res.success) {
        if (res.data && res.data.length) {
          let ids = res.data.map(item => item.id)
          tableInfo.data.map(item => {
            if (ids.includes(item.id)) {
              item.isChoice = true
            }
          })
        }else{
          proxy.$message({
            type: 'warning',
            duration: 3500,
            message: '未查询到符合条件的数据',
            showClose: true,
          })
        }
      }
    })
  })
}
function handlePreviewWin(url){
  window.open(url, '_blank', 'width=1200,height=1200');
}
function handleRemove(index) {
  tableInfo.data[index].udiImageUrl = ''
}
function downFiles(file) {
  console.log(file)
  axios({ method: 'get', url: file, responseType: 'blob' }).then(
    (res) => {
      let blob = res
      let urlL = window.URL.createObjectURL(new Blob([blob], {type: 'image/jpg'}))
      let link = document.createElement('a')
      link.href = urlL
      link.download = file.name
      link.click()
    }
  )
}
function handleMouseOver(){
  hovered.value = true;
}
function handleMouseLeave(){
  hovered.value = false;
}
//导出excel
function exportExcel() {
  let params = proxy.$fn.deepClone(filterInfo.query)
  params.page = false
  params.queryMap = {}
  exportUdiReceivingOrderDetailBind(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp, 'UDI码绑定收货单明细表列表')
    }
  })
}
function handleSave() {
  let params = {
    detailList: tableInfo.data
  }
  creatdUdiReceivingOrderDetailBind(params).then(res => {
    if (res && res.success) {
      shows.value = false
      emit('callback')
    }
  })
}
// 关闭弹窗前的回调
function handleClose() {
  shows.value = false
}
function clearSearch() {
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
  tableInfo.data.map(item => {
    item.isChoice = false
  })
}
function tableRowClassName({ row }) {
  if (row.isChoice) {
    return 'success-row'
  }
  return ''
}
function upDateUpload(obj) {
  //上传图片返回
  let { data, index } = obj
  tableInfo.data[index].udiImageUrl = data[0]
}
function callbackEle() {
  let index = viewImgInfo.value.index
  tableInfo.data[index].udiImageUrl = ''
}
function viewImg(row, index) {
  //查看图片
  if (!row.udiImageUrl) return
  viewImgInfo.value.row = row
  viewImgInfo.value.index = index
  viewImgInfo.value.visible = true
  viewImgInfo.value.list = [
    {
      name: row.udiImageUrl,
      url: action.value + row.udiImageUrl,
      uid: new Date().getTime() + (1 + Math.random()),
    },
  ]
}
setData()
function setData() {
  let obj = {
    commonName: {
      label: '通用名称',
      value: 'commonName',
      componentType: 'input',
      show: false,
      hidden: true,
    },
    udiCode: {
      label: 'UDI码',
      value: 'udiCode',
      componentType: 'input',
      type: 'slot',
      show: false,
      hidden: true,
    },
    udiImageUrl: {
      label: 'UDI图',
      value: 'udiImageUrl',
      componentType: 'input',
      type: 'slot',
      show: false,
      hidden: true,
    },
  }
  tableInfo.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj)
  })
  getCustomize()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'udiBindExtendReceivingOrderDetailList-com.slip.spd.entity.vo.stock.TransferOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.searchList,
        data.detail
      )
      tableInfo.fieldLis = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail,
      )
      filterInfo.query.queryMap = {
        ...filterInfo.query.queryMap,
        ...searchInfo.queryMap,
      }
      filterInfo.copyQueryMap = proxy.$fn.deepClone(filterInfo.query.queryMap)
      filterInfo.searchList = searchInfo.searchList
      filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      slipSelectRequest.value = _slipSelectRequest
      getList()
    }
  })
}

</script>
<style scoped lang="scss">
:deep(.showImage) {
  width: 100%;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  .image {
    max-width: 40px !important;
    max-height: 40px !important;
  }
  .image-tag{
    width: 100%;
    height: 40px;
    position: absolute;
    z-index: 10;
    background: rgba(0,0,0,0.4);
    display: flex;
    align-items: center;
    justify-content: space-around;
  }
}
</style>